<?php
namespace App\Common\Services;

use App\Exceptions\ApiException;
use App\Services\CommonBaseService;
use OSS\Core\OssException;
use OSS\OssClient;

class OssService extends CommonBaseService
{
    /**
     * 上传到云存储
     * @param $filePath
     * @param $fileName
     * @param $etag
     * @param string $type
     * @return string
     * @throws ApiException
     */
    public function uploadToOss($filePath, $fileName, &$etag, $type = 'share_center',$isReName=false)
    {
        if ($etag) {
            $oss = $this->model->where([
                'etag' => strtoupper($etag)
            ])->first();
            if ($oss) {
                @unlink($filePath);
                return $oss['url'];
            }
        }
        $bucket = config('oss.bucketName');
        $ext = pathinfo($fileName, PATHINFO_EXTENSION);
        $oss = new OssClient(
            config('oss.accessKeyId'),
            config('oss.accessKeySecret'),
            config('oss.ossServerInternal')
        );
        $disposition = 'attachment;filename=' . $fileName;
        if (in_array(strtolower($ext), ['jpg', 'jpeg', 'gif', 'png'])) {
            $disposition = "";
        }
        $options = [
            OssClient::OSS_HEADERS => [
                'Cache-Control' => 'max-age=365',
                'Content-Disposition' => $disposition,
//            'Content-Encoding' => 'utf-8',
//            'Content-Language' => 'zh-CN',
                'x-oss-server-side-encryption' => 'AES256',
            ],
        ];
        if($isReName){
            $object = config('oss.ossObject') .
                "/$type/" . date('Y') . "/" . date('md') . "/" . uniqid() . ($ext ? "." . $ext : "");
        }else{
            $object = config('oss.ossObject') .
                "/$type/" . date('Y') . "/" . date('md') . "/" .mt_rand(1000, 9999)."/". uniqid() . ($ext ? "/" . $fileName : "");
        }
        try {
//        print_r([$bucket, $object, $filePath, $options]);die;
            $response = $oss->uploadFile($bucket, $object, $filePath, $options);
            $url = $response['info']['url']??'';
            $url = str_replace(
                config('oss.ossServerInternalHttp').$bucket
                . "." . config('oss.ossServerInternal'),
                config("oss.ossServerHttp") . config('oss.ossServer'),
                $url
            );
            $this->save([
                'etag' => trim($response['etag'], '"')??'',
                'url' => $url,
                'file_size' => filesize($filePath),
            ]);
            @unlink($filePath);
            return $url;
        } catch (OssException $e) {
            throw new ApiException(40008, [
                'message' => $e->getMessage(),
                'code' => $e->getCode()
            ]);
        }
    }
}
